package com.coollang.smartbra.presenter;

import android.graphics.Color;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.RunningActivity;
import com.coollang.smartbra.utils.WalkUtil;

import java.util.ArrayList;

/**
 * @Auther: Timmy
 * @Data: 2017/8/10
 * @Fuction:
 */

public class RunningActivityPresenter {

    private static final String TAG = RunningActivityPresenter.class.getSimpleName();
    private RunningActivity mRunningActivity;
    public AMapLocationClient mLocationClient;
    public AMap mAMap;
    private MyLocationStyle mMyLocationStyle;
    private AMapLocationClientOption mLocationClientOption;
    private static final long LOCATION_TIME_INTERVAL = 1000;
    private Marker mMarkMyLocation;
    private Polyline mPolyline;
    private LatLng mCurrentLatLng;

    public RunningActivityPresenter(RunningActivity runningActivity) {
        mRunningActivity = runningActivity;
    }

    // 初始化mapview
    public void initMap(MapView mapView) {
        if (mAMap == null) {
            mAMap = mapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        mAMap.setLocationSource(mLocationSource);// 设置定位监听

        UiSettings mUiSettings = mAMap.getUiSettings();
        mUiSettings.setLogoPosition(2);//设置高德地图logo位置
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        mUiSettings.setTiltGesturesEnabled(false);
        setMyLocationStyleIcon(true);

        mAMap.setMyLocationEnabled(true);
    }

    private void setMyLocationStyleIcon(boolean b) {
        // 自定义系统定位小蓝点

        mMyLocationStyle = new MyLocationStyle();

        ImageView iv = new ImageView(mRunningActivity);
        FrameLayout.LayoutParams fmIv;
        if (b) {
            fmIv = new FrameLayout.LayoutParams(80, 80);
        } else {
            fmIv = new FrameLayout.LayoutParams(1, 1);
        }
        iv.setImageResource(R.drawable.gps_point);
        iv.setLayoutParams(fmIv);

        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
        mMyLocationStyle.myLocationIcon(markerIcon);// 设置小蓝点的图标
        mMyLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        mMyLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        mMyLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        mMyLocationStyle.anchor(0.5f, 0.9f);
        mAMap.setMyLocationStyle(mMyLocationStyle);
    }

    public void onClickLocation() {
        if (mMapLocation != null) {
            if (mMapLocation.getErrorCode() == 0) {
                //取出经纬度
                LatLng latLng = new LatLng(mMapLocation.getLatitude(), mMapLocation.getLongitude());
                //然后可以移动到定位点,使用animateCamera就有动画效果
                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 19f));
            }
        }
    }

    // ============================ 监听 =================================================
    private LocationSource.OnLocationChangedListener mLocationLinstener;
    private LocationSource mLocationSource = new LocationSource() {
        @Override
        public void activate(OnLocationChangedListener onLocationChangedListener) {
            mLocationLinstener = onLocationChangedListener;

            initLocation();
            setLocationStytle();
        }

        @Override
        public void deactivate() {
            mLocationLinstener = null;
        }
    };

    private void setLocationStytle() {
        // 设置Location模式 , 当前为跟随模式
        // 设置定位的类型为 跟随模式
        //mAMap.setMyLocationStyle(mMyLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW));

        // 定位、但不会移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。
        mAMap.setMyLocationStyle(mMyLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));
    }

    private AMapLocation mMapLocation;
    private double mLocatinLat;
    private double mLocationLon;
    private LatLng currLa;
    private boolean isStart;
    private boolean mIsFirstLocation = true;
    private ArrayList<LatLng> mLocationList = new ArrayList<>();

    private AMapLocationListener mAMapLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    if (mLocationLinstener != null) {
                        mLocationLinstener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                    }
                    mMapLocation = aMapLocation;

                    mLocatinLat = aMapLocation.getLatitude();
                    mLocationLon = aMapLocation.getLongitude();

                    currLa = new LatLng(mLocatinLat, mLocationLon);

                    if (isStart) {
                        if (mIsFirstLocation) {
                            mIsFirstLocation = false;
                            setMyStopLoca(currLa);
                            mLocationList.add(currLa);
                        } else {
                            findBest();
                        }
                    }

                    // 信号问题
                    float accuracy = aMapLocation.getAccuracy();
                    setsetGPSAccuracy(accuracy);
                }
            }
        }
    };

    // ===================================================================================

    public void initLocation() {
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(19f));

        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(mRunningActivity);
            mLocationClientOption = new AMapLocationClientOption();

            // 设置定位模式为高精度模式
            mLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //mLocationClientOption（默认返回地址信息）
            mLocationClientOption.setNeedAddress(true);
            //每两秒定位一次
            mLocationClientOption.setInterval(LOCATION_TIME_INTERVAL);
            mLocationClientOption.setOnceLocation(false);

            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationClientOption.setWifiScan(true);

            // 设置定位监听
            mLocationClient.setLocationListener(mAMapLocationListener);
            // 设置定位参数
            mLocationClient.setLocationOption(mLocationClientOption);
            // 启动定位
            mLocationClient.startLocation();
        }
    }

    private void setMyStopLoca(LatLng latlng) {


        if (mMarkMyLocation == null) {
            MarkerOptions markerOptions = new MarkerOptions();
            // 设置Marker点击之后显示的标题

            markerOptions.setFlat(false);
            markerOptions.anchor(0.5f, 0.7f);
            markerOptions.zIndex(90);
            ImageView iv = new ImageView(mRunningActivity);
            FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(35, 35);
            iv.setImageResource(R.drawable.end);
            iv.setLayoutParams(fmIv);
            BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
            markerOptions.icon(markerIcon);
            markerOptions.position(latlng);
            mMarkMyLocation = mAMap.addMarker(markerOptions);

        } else {
            mMarkMyLocation.setPosition(latlng);
        }
    }

    // 开始的按钮
    private void setStartMarker() {
        mLocationList.add(currLa);

        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currLa, 18f));


        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.setFlat(false);
        markerOptions.anchor(0.5f, 0.7f);

        markerOptions.zIndex(1);
        ImageView iv = new ImageView(mRunningActivity);
        FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(35, 35);
        iv.setImageResource(R.drawable.start);
        iv.setLayoutParams(fmIv);
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
        markerOptions.icon(markerIcon);
        markerOptions.position(currLa);
        mAMap.addMarker(markerOptions);
    }

    private void setEndMarker() {
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currLa, 18f));

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.setFlat(false);
        markerOptions.anchor(0.5f, 0.7f);

        markerOptions.zIndex(1);
        ImageView iv = new ImageView(mRunningActivity);
        FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(35, 35);
        iv.setImageResource(R.drawable.end);
        iv.setLayoutParams(fmIv);
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
        markerOptions.icon(markerIcon);
        markerOptions.position(currLa);
        mAMap.addMarker(markerOptions);
    }

    private LatLng lastLa = new LatLng(0, 0);


    // 计算轨迹
    private void findBest() {

        if (!lastLa.equals(currLa)) {
            // 查看移动的距离 单位为米

            if (lastLa.latitude != 0) {
                float currLength = AMapUtils.calculateLineDistance(lastLa, currLa);
                mRunningActivity.mRunningSettingFragment.movingDistance(currLength / 1000.0f);
            }

            lastLa = currLa;
            mCurrentLatLng = lastLa;
            mLocationList.add(mCurrentLatLng);
            mMarkMyLocation.setPosition(mCurrentLatLng);
            DrawRideTraceTotal();
        }
    }

    // 设置GPS信号
    private void setsetGPSAccuracy(float accuracy) {
        int level = 0;
        if (accuracy > 0) {
            if (accuracy < 48) {
                level = 3;
            } else if (accuracy <= 163 && accuracy >= 48) {
                level = 2;
            } else if (accuracy > 163) {
                level = 1;
            }
        }
        mRunningActivity.setsetGPSAccuracy(level);
    }

    public void startRunning() {
        if (!isStart) {
            setStartMarker();
            isStart = true;
            setMyLocationStyleIcon(false);
        }
    }

    public void stopRunning() {
        if (isStart) {
            isStart = false;
            // setEndMarker();

            // 停止定位, 显示地图
            stopLocation();
        }
    }

    private void stopLocation() {
        mLocationClient.stopLocation();
    }

    // 绘制轨迹线
    private void DrawRideTraceTotal() {

        if (mPolyline != null) {
            mPolyline.remove();
            mPolyline = null;
        }

        PolylineOptions polylineOptions = new PolylineOptions();
        polylineOptions.addAll(mLocationList);
        // polylineOptions.visible(true).width(15).zIndex(200);

        // 线段的宽度,z轴的角度
        polylineOptions.visible(true).width(15).zIndex(200);
        // 加入对应的颜色,使用colorValues 即表示使用多颜色，使用color表示使用单色线
        polylineOptions.colorValues(WalkUtil.getColorList(mLocationList.size() / 144 + 1, mRunningActivity));
        //加上这个属性，表示使用渐变线
        polylineOptions.useGradient(true);
        mPolyline = mAMap.addPolyline(polylineOptions);
    }

    public ArrayList<LatLng> getList() {
        return mLocationList;
    }

}
